<template>
  <el-row :gutter="20">
    <el-col
      :span="6"
      style="
        display: flex;
        justify-content: center;
        align-items: center;
      "
    >
      <Aselect
        :options="options"
        v-model="pro"
        size="small"
        @change="changePro"
      ></Aselect>
    </el-col>
    <el-col
      :span="1"
      style="
        display: flex;
        justify-content: center;
        align-items: center;
      "
    >
      <el-icon><SemiSelect /></el-icon>
    </el-col>
    <el-col
      :span="13"
      style="
        display: flex;
        justify-content: center;
        align-items: center;
      "
    >
      <Aselect
        :options="cityOpt"
        :multiple="multiple"
        v-model="city"
        size="small"
        @change="changeCity"
      ></Aselect>
      <div style="width: 20px"></div>
      <el-button
        type="primary"
        size="small"
        v-if="multiple"
        @click="allCity"
        :disabled="!pro.length"
        >选择所有城市</el-button
      >
    </el-col>
  </el-row>
</template>

<script setup>
import Aselect from "./Aselect.vue";
import zh from "@/assets/js/zh.js";
import { onMounted, ref, watch } from "vue";

const props = defineProps({
  // 多选城市
  multiple: {
    typeof: Boolean,
    default: true
  },
  modelValue: {
    typeof: Object,
    default: {
      pro: "",
      city: null
    }
  }
});

const emit = defineEmits({
  ["update:modelValue"](value) {
    return value;
  }
});

const options = ref([]);
const cityOpt = ref([]);

const pro = ref("");
const city = ref(null);

function allCity() {
  city.value = cityOpt.value.map((res) => {
    return res.value;
  });
  const address = {};
  address.pro = pro.value;
  address.city = city.value;
  emit("update:modelValue", address);
}

onMounted((res) => {
  // 循环查找省
  const opt = Object.keys(zh[86]).map((res) => {
    return {
      label: zh[86][res],
      value: res
    };
  });
  options.value = opt;
});

function changePro(e) {
  const opt = Object.keys(zh[e]).map((res) => {
    return {
      label: zh[e][res],
      value: res
    };
  });
  cityOpt.value = opt;
  city.value = null;
  const address = {};
  address.pro = e;
  address.city = city.value;
  emit("update:modelValue", address);
}

function changeCity(e) {
  const address = {};
  address.pro = pro.value;
  address.city = e;
  emit("update:modelValue", address);
}

watch(
  () => props.modelValue,
  (val) => {
    pro.value = val?.pro;
    city.value = val?.city;
    if (pro.value.length) {
      const opt = Object.keys(zh[pro.value]).map((res) => {
        return {
          label: zh[pro.value][res],
          value: res
        };
      });
      cityOpt.value = opt;
    }
  },
  {
    immediate: true
  }
);
</script>

<style></style>
